package service;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Date;

import model.QuestionModel;
import model.SourcePageModel;

import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import entity.Question;
import entity.IpSocket;
import entity.Source;

public class GetUrlThread extends Thread {

	SourcePageModel sourceModel = null;
	Date date;

	public GetUrlThread() {

	}

	public synchronized void doItSynchronized() {
		Document doc = null;
		QuestionModel questionModel = new QuestionModel();
		sourceModel = new SourcePageModel();
		Source source = sourceModel.get();
		String url = "http://efreedom.com/Questions/";
		IpSocket mySocket = new IpSocket();

		int current = Integer.valueOf(source.getCurrent());		
		try {
			doc = util.SocketContentHandle.getSiteContentBySocket(
					"efreedom.com", "", url + String.valueOf(current),
					mySocket.get());
		} catch (UnknownHostException ex) {
			System.out
					.println("UnknownHostException occur when get question url !");
		} catch (IOException ex) {
			System.out.println("IOException occur when get question url !");
		}

		Elements titles = doc.select(".topicTitle a");
		try {
			if (titles.size() > 0) {
				for (int i = 0; i < titles.size(); i++) {
					Question obj = new Question();
					obj.setUrl("http://efreedom.com"
							+ titles.get(i).attr("href"));
					date = new Date();
					obj.setLastUpdateDate(date);
					obj.setDoc(date);
					obj.setHadContent(0);
					obj.setLang(null);
					if (questionModel.isGotten(obj.getUrl())) {
						System.out.println("Question had already got !");
					} else {
						if (obj.isValidUrl()) {
							questionModel.save(obj);
						} else {
							System.out.println("Url's not valid !");
						}
					}
				}
				current -= 1;
				source.setCurrent(String.valueOf(current));
				sourceModel.save(source);
				System.out.println("Get one page success ! Current page : "
						+ current);
			}
		} catch (Exception e) {
			System.out.println("Error occur !");
		}	
	}

	public void run() {
		doItSynchronized();
	}
}
